/*
 * @Author: taosong 2289713738@qq.com
 * @Date: 2024-01-02 21:03:53
 * @LastEditors: taosong 2289713738@qq.com
 * @LastEditTime: 2024-01-02 21:41:09
 * @FilePath: \ele-h5\src\use\useParent.ts
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
import { inject, type InjectionKey, getCurrentInstance, onUnmounted } from 'vue'
import type { Child } from './useChildren'
export type ParentProvide<T> = T & {
  link(instance: Child): void
  unlink(instance: Child): void
  [key: string]: any
}

export const useParent = <T>(key: InjectionKey<ParentProvide<T>>) => {
  const parent = inject(key, null)

  if (!parent) {
    return {
      parent: null
    }
  }

  const instance = getCurrentInstance()
  const { link, unlink } = parent
  link(instance as any)
  onUnmounted(() => unlink(instance as any))

  return parent
}
